<template>
  <!-- Conditionally render based on browser support -->
  <UnsupportedBrowserView v-if="isSupported === false" />
  
  <!-- Render the main app layout only if supported -->
  <MainLayout v-else-if="isSupported === true">
    <!-- CompatibilityCheck is removed, logic is handled here now -->
    <!-- Toast warning for transition API is triggered from the hook below -->
    <!-- Restore DndProvider -->
    <DndProvider :backend="HTML5Backend">
      <el-config-provider :size="size" :locale="locale">
        <RouterView v-slot="{ Component }">
          <!-- 
            DETAILED COMMENT: 
            The <transition> component provides animation for route changes.
            Previously, `mode="out-in"` was used here. This mode ensures the old
            component finishes its leaving transition BEFORE the new component 
            starts its entering transition.
            
            However, this `out-in` mode caused a critical issue specifically when 
            navigating to the FileManagerView. The delayed mounting of FileManagerView
            (due to waiting for the old component to leave) combined with its immediate 
            asynchronous data loading in `onMounted` seemed to create a timing conflict 
            with Vue Router's internal state management after navigation completion.
            This resulted in an unexpected navigation back to the previous route (home).

            Removing the `mode="out-in"` attribute (falling back to the default mode 
            or potentially `in-out`) resolves this issue because the component mounting 
            timing is different, avoiding the conflict.
          -->
          <transition name="fade"> 
            <component :is="Component" />
          </transition>
        </RouterView>
      </el-config-provider>
    </DndProvider>
  </MainLayout>

  <!-- Optional: Show a loading indicator while checking -->
  <div v-else class="loading-check">
     <!-- Add a spinner or loading text here if desired -->
     <!-- Checking browser compatibility... -->
  </div>
</template>

<script setup lang="ts">
import { computed, provide, onMounted, watch } from 'vue' // Import watch
import type { Ref } from 'vue'
import { useSettingsStore } from '@/stores/settingsStore'
import { RouterView } from 'vue-router'
import MainLayout from '@/components/layout/MainLayout.vue'
import UnsupportedBrowserView from '@/views/UnsupportedBrowserView.vue' // Import the new view
import { useBrowserCompatibility } from '@/composables/useBrowserCompatibility' // Import the composable
import { ElConfigProvider } from 'element-plus'
import type { ComponentSize } from 'element-plus'
import { useEditorStore } from '@/stores/editorStore.ts'
import { useFileManagerStore } from '@/stores/fileManagerStore.ts'
// @ts-ignore - Suppress type errors for DndProvider if definitions are missing/incorrect
import { DndProvider } from 'vue3-dnd' // Restore DndProvider import
// @ts-ignore - Suppress type errors for HTML5Backend if definitions are missing/incorrect
import { HTML5Backend } from 'react-dnd-html5-backend' // Restore backend import
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
import { useToast } from 'vue-toastification'
import { useRouter } from 'vue-router'
import AppHeader from '@/components/layout/AppHeader.vue'

const settingsStore = useSettingsStore()
const editorStore = useEditorStore()
const fileManagerStore = useFileManagerStore()
const toast = useToast()
const router = useRouter()
const isDark = computed(() => settingsStore.darkMode)
const size = computed((): ComponentSize => settingsStore.componentSize)

// Use the compatibility composable
const {
  isSupported,
  browserInfo,
  requiresTransitionWarning,
  showTransitionWarningToast,
  requiresHasPseudoClassWarning,
  showHasPseudoClassWarningToast
} = useBrowserCompatibility();

// Define locale based on settings or default
const locale = computed(() => {
  // Assuming settingsStore has a language property, e.g., settingsStore.language === 'en'
  // Replace with your actual language setting logic
  // Example: Defaulting to Chinese (zhCn)
  return zhCn;
});

// Computed property for dynamic class binding
const themeClass = computed(() => settingsStore.darkMode ? 'dark' : 'light');

onMounted(() => {
  console.log("[App.vue] Mounted. Checking browser compatibility...");
  console.log("[App.vue] Browser Info:", browserInfo.value);
  console.log("[App.vue] Is Supported:", isSupported.value);
  console.log("[App.vue] Requires Transition Warning:", requiresTransitionWarning.value);
  console.log("[App.vue] Requires :has() Warning:", requiresHasPseudoClassWarning.value);

  // Redirect if browser is not supported at all
  if (isSupported.value === false) {
    console.warn("[App.vue] Browser not supported, redirecting...");
    router.replace({ name: 'UnsupportedBrowser' });
    return; // Stop further checks if redirected
  }

  // Show transition warning if needed
  if (requiresTransitionWarning.value) {
    console.log("[App.vue] Showing transition warning toast...");
    showTransitionWarningToast();
  }

  // Show :has() warning if needed
  if (requiresHasPseudoClassWarning.value) {
     console.log("[App.vue] Showing :has() pseudo-class warning toast...");
     showHasPseudoClassWarningToast();
  }

  settingsStore.applyTheme()
  // Example: Load initial root folder items when app mounts
  // Check if items are already loaded maybe?
  // --- COMMENT OUT THE PRE-LOADING LOGIC ---
  // if (fileManagerStore.currentItems.length === 0 && fileManagerStore.currentFolderId === null) {
  //     console.log('[App.vue onMounted] Loading initial root folder items...');
  //     fileManagerStore.navigateToFolder(null);
  // }
})

// Watch for theme changes to apply class to body
watch(themeClass, (newClass, oldClass) => {
    if (oldClass) document.body.classList.remove(oldClass);
    if (newClass) document.body.classList.add(newClass);
}, { immediate: true });

// Watch for changes in settings store themeColor to update CSS variable
watch(() => settingsStore.themeColor, (newColor) => {
  document.documentElement.style.setProperty('--el-color-primary', newColor);
}, { immediate: true });

provide<Ref<boolean>>('isDark', isDark)
</script>

<style lang="scss">
/* Router transition styles (keep these) --- RESTORE TRANSITION STYLES */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.app-container {
  position: relative;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: var(--el-bg-color);
  color: var(--el-text-color-primary);
  transition: background-color 0.3s ease, color 0.3s ease;
}

/* --- REMOVED: View Transition Styles for Theme Change --- */
/* Animation is now handled by Web Animations API in settingsStore */

// Keep base dark/light mode styles
html.dark {
  color-scheme: dark;
  // Ensure dark mode variables are defined (e.g., via Element Plus dark theme import)
}

html:not(.dark) {
  color-scheme: light;
}

/* --- ADD VIEW TRANSITION CSS HERE (or in a global CSS file) --- */

/* Optional loading indicator style */
.loading-check {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  font-size: 1.2em;
  color: var(--el-text-color-secondary);
}
</style>